#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const os = require('os');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

console.log('🚀 手机文件上传工具 - 初始化设置');
console.log('=====================================');
console.log(`系统: ${os.type()} ${os.arch()}`);
console.log(`Node.js: ${process.version}`);
console.log('');

// 默认配置
const defaultConfig = {
  uploadDir: './uploads',
  port: 3001,
  clientPort: 3000,
  maxFileSize: 'unlimited',
  maxFiles: 50,
  allowedFileTypes: ['image/*', 'video/*'],
  autoCreateDir: true
};

function askQuestion(question, defaultValue = '') {
  return new Promise((resolve) => {
    const prompt = defaultValue ? `${question} (默认: ${defaultValue}): ` : `${question}: `;
    rl.question(prompt, (answer) => {
      resolve(answer.trim() || defaultValue);
    });
  });
}

function getDefaultUploadDir() {
  const platform = os.type();
  if (platform === 'Darwin') { // macOS
    return path.join(os.homedir(), 'Downloads', 'mobile-uploads');
  } else if (platform === 'Windows_NT') { // Windows
    return path.join(os.homedir(), 'Downloads', 'mobile-uploads');
  } else { // Linux
    return path.join(os.homedir(), 'mobile-uploads');
  }
}

async function setup() {
  try {
    console.log('📁 配置上传目录');
    console.log('-------------------');
    
    const defaultDir = getDefaultUploadDir();
    const uploadDir = await askQuestion('请输入文件上传目录的完整路径', defaultDir);
    
    console.log('\n🌐 网络配置');
    console.log('-------------');
    
    const port = await askQuestion('后端服务器端口', '3001');
    const clientPort = await askQuestion('前端服务器端口', '3000');
    
    console.log('\n📊 上传限制');
    console.log('-------------');
    
    const maxFiles = await askQuestion('最大同时上传文件数', '50');
    
    // 创建配置对象
    const config = {
      ...defaultConfig,
      uploadDir: uploadDir,
      port: parseInt(port),
      clientPort: parseInt(clientPort),
      maxFiles: parseInt(maxFiles)
    };
    
    // 保存配置文件
    fs.writeFileSync('config.json', JSON.stringify(config, null, 2));
    console.log('\n✅ 配置文件已保存到 config.json');
    
    // 创建上传目录
    if (config.autoCreateDir) {
      const resolvedDir = path.isAbsolute(uploadDir) ? uploadDir : path.resolve(uploadDir);
      if (!fs.existsSync(resolvedDir)) {
        fs.mkdirSync(resolvedDir, { recursive: true });
        console.log(`✅ 已创建上传目录: ${resolvedDir}`);
      } else {
        console.log(`📁 上传目录已存在: ${resolvedDir}`);
      }
    }
    
    console.log('\n🎉 设置完成！');
    console.log('================');
    console.log('下一步操作:');
    console.log('1. 运行 npm install (如果还没安装依赖)');
    console.log('2. 运行 npm run dev 启动服务');
    console.log('3. 在手机浏览器打开显示的网址');
    console.log('');
    console.log('💡 提示:');
    console.log('- 可以随时编辑 config.json 文件来修改配置');
    console.log('- 确保手机和电脑在同一WiFi网络下');
    console.log('- 如需修改配置，重新运行 node setup.js');
    
  } catch (error) {
    console.error('❌ 设置过程中发生错误:', error.message);
  } finally {
    rl.close();
  }
}

// 检查是否已有配置文件
if (fs.existsSync('config.json')) {
  rl.question('检测到已有配置文件，是否重新配置？(y/N): ', (answer) => {
    if (answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes') {
      setup();
    } else {
      console.log('保持现有配置，退出设置。');
      rl.close();
    }
  });
} else {
  setup();
} 